<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Auth;

class Course extends Model
{
    use SoftDeletes;
    protected $guarded = [];
    protected $casts = [
        'is_best' => 'boolean',
        'is_required' => 'boolean',
        'is_on_sale' => 'boolean',
        'price' => 'double'
    ];
    protected $appends = ['category_name', 'purchased'];

    public function getPurchasedAttribute()
    {
        if (Auth::id()) {
           if($this->userCourses()
                ->where('user_id', Auth::id())
                ->where('pay_status', 1)
                ->count()) {
               return true;
           }
        }
        return false;
    }
    public function getCategoryNameAttribute()
    {
        $category = $this->attributes['category_id'];
        if ($category == 1)
            return '文化经典';
        if ($category == 2)
            return '能量禅修';
        if ($category == 3)
            return '易经风水';
        if ($category == 4)
            return '领袖商道';
        if ($category == 5)
            return '健康养生';
        if ($category == 6)
            return '积分课程';
        if ($category == 7)
            return '进阶高级';
        if ($category == 8)
            return '咨询老师';
        return $category;
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function catalogs()
    {
        return $this->hasMany(CataLog::class);
    }

    public function userCourses()
    {
        return $this->morphMany(UserCourse::class, 'courseable');
    }
}
